<template>
  <div class="video-management">
    <div class="header">
      <h2>비디오 관리</h2>
      <el-button type="primary" @click="showUploadDialog = true">
        <el-icon><Upload /></el-icon>
        비디오 업로드
      </el-button>
    </div>

    <!-- 视频列表 -->
    <el-table :data="videos" v-loading="loading" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="커버" width="120">
        <template #default="{ row }">
          <img
            v-if="row.coverUrl"
            :src="`${API_BASE}${row.coverUrl}`"
            style="width: 80px; height: 45px; object-fit: cover; border-radius: 4px;"
            alt="커버"
          />
          <span v-else class="no-cover">커버 없음</span>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="제목" min-width="200" />
      <el-table-column prop="channel.name" label="채널" width="150" />
      <el-table-column label="파일 크기" width="120">
        <template #default="{ row }">
          {{ formatFileSize(row.sizeBytes) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="상태" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 'published' ? 'success' : 'warning'">
            {{ row.status === 'published' ? '게시됨' : '초안' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="생성 시간" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="작업" width="120" fixed="right">
        <template #default="{ row }">
          <el-button
            type="danger"
            size="small"
            @click="deleteVideo(row)"
            :loading="row.deleting"
          >
            삭제
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchVideos"
        @current-change="fetchVideos"
      />
    </div>

    <!-- 업로드 대화상자 -->
    <el-dialog v-model="showUploadDialog" title="비디오 업로드" width="600px">
      <el-form :model="uploadForm" label-width="80px">
        <el-form-item label="제목" required>
          <el-input v-model="uploadForm.title" placeholder="비디오 제목을 입력하세요" />
        </el-form-item>
        <el-form-item label="설명">
          <el-input
            v-model="uploadForm.description"
            type="textarea"
            :rows="3"
            placeholder="비디오 설명을 입력하세요 (선택사항)"
          />
        </el-form-item>
        <el-form-item label="채널" required>
          <el-select v-model="uploadForm.channelId" placeholder="채널을 선택하세요" style="width: 100%">
            <el-option
              v-for="channel in channels"
              :key="channel.id"
              :label="channel.name"
              :value="channel.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="비디오 파일" required>
          <el-upload
            ref="videoUpload"
            :auto-upload="false"
            :limit="1"
            accept=".mp4,.mov"
            :on-change="handleVideoChange"
            :file-list="videoFileList"
          >
            <el-button type="primary">비디오 파일 선택</el-button>
            <template #tip>
              <div class="el-upload__tip">
                mp4/mov 파일만 업로드 가능하며, 2GB를 초과할 수 없습니다
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="커버 이미지">
          <el-upload
            ref="coverUpload"
            :auto-upload="false"
            :limit="1"
            accept=".jpg,.jpeg,.png,.webp"
            :on-change="handleCoverChange"
            :file-list="coverFileList"
          >
            <el-button>커버 이미지 선택</el-button>
            <template #tip>
              <div class="el-upload__tip">
                jpg/png/webp 형식 지원 (선택사항)
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showUploadDialog = false">취소</el-button>
        <el-button
          type="primary"
          @click="uploadVideo"
          :loading="uploading"
          :disabled="!canUpload"
        >
          업로드
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import request from '@/utils/request'

const API_BASE = (import.meta as any)?.env?.VITE_API_BASE_URL || ''

// 响应式数据
const loading = ref(false)
const videos = ref<any[]>([])
const channels = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

const showUploadDialog = ref(false)
const uploading = ref(false)
const uploadForm = ref({
  title: '',
  description: '',
  channelId: ''
})

const videoFileList = ref<any[]>([])
const coverFileList = ref<any[]>([])

// 计算属性
const canUpload = computed(() => {
  return uploadForm.value.title &&
         uploadForm.value.channelId &&
         videoFileList.value.length > 0
})

// 方法
const fetchVideos = async () => {
  loading.value = true
  try {
    const response = await request.get('/api/admin/videos', {
      params: {
        page: currentPage.value,
        limit: pageSize.value
      }
    })
    videos.value = response.data.videos
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('获取视频列表失败')
  } finally {
    loading.value = false
  }
}

const fetchChannels = async () => {
  try {
    const resp = await request.get('/api/admin/channels', { params: { limit: 200 } })
    channels.value = resp.data.channels
  } catch (error) {
    ElMessage.error('获取频道列表失败')
  }
}

const handleVideoChange = (file: any) => {
  videoFileList.value = [file]
}

const handleCoverChange = (file: any) => {
  coverFileList.value = [file]
}

const uploadVideo = async () => {
  if (!canUpload.value) return

  uploading.value = true
  try {
    const formData = new FormData()
    formData.append('title', uploadForm.value.title)
    formData.append('description', uploadForm.value.description)
    formData.append('channelId', uploadForm.value.channelId)
    formData.append('video', videoFileList.value[0].raw)

    if (coverFileList.value.length > 0) {
      formData.append('cover', coverFileList.value[0].raw)
    }

    await request.post('/api/admin/videos/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    ElMessage.success('视频上传成功')
    showUploadDialog.value = false
    resetUploadForm()
    fetchVideos()
  } catch (error) {
    ElMessage.error('视频上传失败')
  } finally {
    uploading.value = false
  }
}

const deleteVideo = async (video: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这个视频吗？', '确认删除', {
      type: 'warning'
    })

    video.deleting = true
    await request.delete(`/api/admin/videos/${video.id}`)
    ElMessage.success('删除成功')
    fetchVideos()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  } finally {
    video.deleting = false
  }
}

const resetUploadForm = () => {
  uploadForm.value = {
    title: '',
    description: '',
    channelId: ''
  }
  videoFileList.value = []
  coverFileList.value = []
}

const formatFileSize = (bytes: string | null) => {
  if (!bytes) return '-'
  const size = parseInt(bytes)
  if (size < 1024) return size + ' B'
  if (size < 1024 * 1024) return (size / 1024).toFixed(1) + ' KB'
  if (size < 1024 * 1024 * 1024) return (size / (1024 * 1024)).toFixed(1) + ' MB'
  return (size / (1024 * 1024 * 1024)).toFixed(1) + ' GB'
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  fetchVideos()
  fetchChannels()
})
</script>

<style scoped>
.video-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.no-cover {
  color: #999;
  font-size: 12px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
